var cacheBnos = new Array();
var clickQueryBtn = false;
var waybill_signpic;
var validMobile_signpic;
$(document).ready(function(){	
	if (getL() == '2') {
		$("#pagingBar").css("style", "display:");
	} else {
		$("#pagingBar").css("style", "display:none");
	}
	
	//运单查询页表单验证 
	$("#waybill_members").click(function() {
		var waybillMembers = $("#waybill_members");
		if(waybillMembers.val() == i18n.waybill_number_tips){
			waybillMembers.val("");
		}
	});
	
	$("#waybill_members").focusout(function() {
		var waybillMembers = $("#waybill_members");
		if(waybillMembers.val() == ""){
			waybillMembers.val(i18n.waybill_number_tips);
		} 
	});
	
	$("#waybillQryButton").click(function() {
		clickQueryBtn = true;
		var waybillMembers = $("#waybill_members");
		var waybillMembers_message = $("#waybillMembers_message");
		if(waybillMembers.val() == i18n.waybill_number_tips || waybillMembers.val() == ""){
			waybillMembers_message.text(i18n.waybill_number_empty).addClass("Validform_wrong");
        	return ;
		}
		var listl = waybillMembers.val().split(";");
		var list = new Array();
		var index = 0;
		if(listl!=null && listl.length>0){
			for (var i=0;i<listl.length;i++) {
				while(null == $.trim(listl[i]) || "" == $.trim(listl[i])){
					i++;
					if(i>=listl.length){
						i--;
						break;
					}
				}
				if(null != $.trim(listl[i]) && "" != $.trim(listl[i])){
					list[index] = $.trim(listl[i]);
					index++;
				}
				
			}
		}
		if (list.length > 20) {
			waybillMembers_message.text(i18n.waybill_number_exceeded).addClass("Validform_wrong");
        	return ;
		}
		
		var msg1;
		var msg2;
		for (var i=0;i<list.length;i++) {
			if ($.trim(list[i]).length!=12&&$.trim(list[i]).length!=0) {
				msg1 = i18n.waybill_length_constraint;
				waybillMembers_message.text(msg1.replace("%count%",i+1)).addClass("Validform_wrong");
				$("#waybill_members").focus();
				return;
			}
			if (isNaN($.trim(list[i]))) {
				msg2 = i18n.waybill_character_constraint;
				waybillMembers_message.text(msg2.replace("%count%",i+1)).addClass("Validform_wrong");
				$("#waybill_members").focus();
				return;
			}
		}
		
		// 运单号去重
		var newList = listUniq(list);
		
		// 缓存运单号
		if(null != cacheBnos && cacheBnos.length == newList.length && cacheBnos.sort().toString() == newList.sort().toString()) {
			return;
		}
		cacheBnos = newList;
		
		var l = getL();
		// 已登录或者已下过单，则存在userId,保存快件历史
		if (l == 2 || l == 3) {
			var data = "bnos=" + newList;
			syncCallService("/service/waybill/history", "post", "json", data, function(data) {
//				if("success" == data) {
//					getMyWaybillHistory(list);
//				}
			},function() {
				sfAlert(i18n.errorLoding + i18n.symbol_exclamation);
				return;
		});
		}
		
//		getMyWaybillHistoryNew(newList);
		getMyWaybillHistory(newList);
	});
	
	$("#waybill_members").keyup(function(event) {
		$("#waybill_members").attr("value", $("#waybill_members").val().replace(/[^{0-9}]/g,''));
		var count = Math.floor($.trim($("#waybill_members").val()).length / 12);
		var newValue = '';
		var oldValue = $.trim($("#waybill_members").val());
		for(var i = 0;i < count; i ++) {
			newValue = newValue + oldValue.substr(i*12,12) + ';';
		}
		var result = '';
		if(newValue.slice(0, newValue.length-1).length == 0) {
			result = oldValue.substr(count*12);
		} else {
			result = newValue.slice(0, newValue.length-1) + ';' + oldValue.substr(count*12);
		}
		$("#waybill_members").attr("value", result);
		if(result != '' && result.length > 0) {
			$("#waybillMembers_message").text('').removeClass("Validform_wrong");
		}
	});
	
	$("#verifyCode").keyup(function(event) {
		$("#verifyCode").attr("value", $("#verifyCode").val().replace(/[^\r{0-9,a-z,A-Z}]/g,''));
	});
	

	$("#_send_verifycode_span").data("active",true);
	$("#_send_verifycode_span").click(function(){
		if($("#_send_verifycode_span").data("active") == true)sendSMS();
	});
});

/**
 * 运单号去重
 * 
 */
function listUniq(list) {
	var newList = new Array();
	var tArray = function(i,arr){
		var yap = false;
		for(var j = 0;j < arr.length;j++){
			if(arr[j] == i){yap=true;break;};
		}
		if(!yap) arr.push(i);
	};
	for(var t=0;t<list.length;t++){
		tArray(list[t],newList);
	}
	return newList;
}

// for myWaybillHistory

$(document).ready(function() {
	// 全选
	$('#checkAll').attr("checked", false);
	$('#checkAll').click(function() {
		var isChecked = this.checked;
		$('input[type="checkbox"]').each(function(i, item) {
			this.checked = isChecked;
		});
	});
	
	// 删除
	$('#deleteWaybillHis').click(function(){
		var hasSelectedItems = checkSelected();
		if (!hasSelectedItems) {
			sfAlert(i18n.waybill_select_at_least_one);
			return;
		}
		var selectedWaybillHis = getSelectedWaybillHistorys();
		sfConfirm(i18n.waybill_delete_confirmation + i18n.symbol_question + i18n.myorder_waybillno + i18n.symbol_colon + "<BR/>"+ selectedWaybillHis, 
			function() {
				var url = "/service/waybill/history/"+selectedWaybillHis;
				var type = "delete";
				var dataType = 'json';
//				var data = "bnos=" + selectedWaybillHis;
				asyncCallService(url, type, dataType, null, function(data) {
					if("success" == data) {
//						getMyWaybillHistoryNew('');
						getMyWaybillHistory('');
						$('#checkAll').attr("checked", false);
					}
				}, function() {
		
				});
			}, function() {
			});
		
		
	});
	var wbno = getUrlParam("wbpic");
	var bno = getUrlParam("bno");
	if(toCheckSignPic()){
		if(getL() != '2'){
			location.href = "/cn/sc/login.html?url=/cn/sc/waybill/waybill_query.html?wbpic="+wbno;
			return;
		}
		bno = wbno;
	}
	if (bno == null || $.trim(bno) == null ||($.trim(bno).length != 12 && $.trim(bno).length != 0 && isNaN(bno))) {
		var l = getL();
		// 已登录显示快件历史
		if (l == 2) {
			if(toCheckSignPic()){
				var bnoList = new Array();
				bnoList[0] = $.trim(bno);
				getMyWaybillHistory(bnoList);	
			}else{
				getMyWaybillHistory('');
			}
		} else {
			showNoWaybillHisRecord();
		}
	} else {
		var bnoList = new Array();
		bnoList[0] = $.trim(bno);
		getMyWaybillHistory(bnoList);
		$('html,body').animate({scrollTop: $("#query_result_msg").offset().top}, 500);
	}
	

});

/**
 * 获取URL参数值
 * @param {} name
 * @return {}
 */
function getUrlParam(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg);  //匹配目标参数
	if (r!=null) {
		return unescape(r[2]);
	}
	return null; //返回参数值
}

/**
 * 评价收派员
 * 
 */
function showEvaluation(clickid) {
	var tips_dialog = art.dialog({
		title : false,
		padding : 0,
		follow : clickid,
		content : document.getElementById('evaluat_content')
	});
	var tips_html = '<div class="evaluat">'
				+ '<form id="evalutionForm">'
				+ '<label><input type="radio" name="evaluat" /> <img src="/resources/css/'
				+ i18n.name
				+ '/resources/img/face_smile.gif" alt="' + i18n.waybill_praise + '" /> ' + i18n.waybill_praise + i18n.symbol_exclamation + '</label>'
				+ '<label class="ml20"><input type="radio" name="evaluat" /> <img src="/resources/css/'
				+ i18n.name
				+ '/resources/img/face.gif" alt="' + i18n.waybill_getaway_reviews + '" /> ' + i18n.waybill_getaway_reviews + i18n.symbol_exclamation + '</label>'
				+ '<label class="ml20"><input type="radio" name="evaluat" /> <img src="/resources/css/'
				+ i18n.name + '/resources/img/face_sad.gif" alt="' + i18n.waybill_bad_reviews + '" /> ' + i18n.waybill_bad_reviews + i18n.symbol_exclamation + '</label>'
				+ '</form>' + '</div>';
	tips_dialog.content(tips_html);
	$("#evalutionForm").children().click(function(){
		tips_dialog.close();
	});
}

/**
 * 获取选中的快件历史记录
 */
function getSelectedWaybillHistorys() {
	var waybillSelecteds = "";
	$('input:checkbox[name="checkbox_waybill"]').each(function(i, item){
		var waybillNo = '';
		 if($(this).attr("checked")){
		 	waybillNo = $(this).val();
		 }
		if ("" == waybillSelecteds) {
			waybillSelecteds = waybillNo;
		} else if("" != waybillNo) {
			waybillSelecteds += "," + waybillNo;
		}
	});
	return waybillSelecteds;
}

/**
 * 检查是否有选中项
 */
function checkSelected() {
	var hasSelectedItems = false;
	$('input[type="checkbox"]').not("#checkAll").each(function(i, item) {
		if (this.checked) {
			hasSelectedItems = true;
			return true;
		}
	});
	return hasSelectedItems;
}

/** 获取我的快件历史 */
function getMyWaybillHistory(bnos) {
	
	var url = "/service/waybill/n0login/history";
	if(!clickQueryBtn&&toCheckSignPic()){
		if(getL() != '2'){
			location.href = "/cn/sc/login.html?url=/cn/sc/waybill/waybill_query.html?wbpic="+bnos;
			return;
		}
		//url = "/service/waybill/n0login/wbpichistory";
	}
	var type = "get";
	var dataType = 'json';
	var serachBnos="bnos=" + bnos;
	var data = serachBnos + "&" + $("#myWaybillHistoryForm").serialize();

	syncCallService(url, type, dataType, data, function(data) {

		var myWaybillHistoryTable = $("#divMyWaybillHistory");

		myWaybillHistoryTable.empty();
		var resbnos = "";
		if(data.result != null && data.result != ''){
			$.each(data.result, function(i, item) {
				resbnos += item.bno+",";
				var location = (null == item.loaction) ? i18n.waybill_without_statusInfo : item.loaction;
				var state = (null == item.state) ? "4" : item.state;
				var sender = (null == item.sender) ? "" : item.sender;
				var receiver = (null == item.receiver) ? "" : item.receiver;
				// “0”=快件历史，“1”=快件结果
				var showClass = ("0" == item.isHistory) ? "" : "statesShow";
				var showDetail = ("0" == item.isHistory) ? "showDetailR" : "showDetailH";
				var prodName=item.prodName;
				if(prodName==null || prodName=='' ||prodName=='null'){
					prodName='';
				}
				if(location!=i18n.waybill_without_statusInfo){
					for(var i = 0 ; i<item.steps.length; i++){
						if((item.steps[i].remark.indexOf('运单资料')>-1&&item.steps[i].remark.indexOf('签收图')>-1)||(item.steps[i].remark.indexOf('運單資料')>-1&&item.steps[i].remark.indexOf('簽收圖')>-1)){
							item.steps.splice(i,1);
						}
					}
					if((location.indexOf('运单资料')>-1&&location.indexOf('签收图')>-1)||(location.indexOf('運單資料')>-1&&location.indexOf('簽收圖')>-1)){
						location = item.steps[item.steps.length-1].remark;
					}
				}
				var th = '<div class="blockbox mt10">'
					+'<div class="blockbox-title title_style1">'
					+'<div class="block-title-ct clearfix">'
					+'<div class="ct-left">' +
					'<label>' +
					'<input type="checkbox" name="checkbox_waybill" value="'+item.bno+'" />' +
					'</label>' +
					'<span class="waybill-num">' + i18n.myorder_waybillno + i18n.symbol_colon + item.bno + '<span>(' + location + ')</span></span>' +
					'<B><font style="font-size:18px"><span style="padding-left: 60px;" id="prodName_'+item.bno+'" name="prodNames">' +prodName+'</font></span></B>'+
					'</div>'+
					'<div class="ct-right">'+
					'<a class="unl white mr30" href="javascript:showsignPic(\''+item.bno+'\')" >'+"查看回单图片"+'</a>' +
					'<a class="unl white mr30" href=/'+i18n.name+'/subscription/mail_subscription.html?bno='+item.bno+'>'+i18n.waybill_subscribe_email+'</a>' +
					'<a class="btn-statesInfoHide ' + showClass + '" title="'+i18n.waybill_view_details+'" id="'+showDetail+'"></a>' +
					'</div>'
					+'</div>'
					+'</div>';
				myWaybillHistoryTable.append(th + createWaybillRouteNode(item.bno, state, sender, receiver, item.steps, item.isHistory) + '</div>');
				showMiddleNode(item.bno, state, item.steps, 150);
			});
		}
		if(!clickQueryBtn&&toCheckSignPic()){
			if(resbnos.indexOf(bnos)>-1){
				showsignPic(bnos);
			}else{
				sfAlert("非常抱歉，暂未能查询到运单"+bnos+"的信息，请稍后再尝试，谢谢！");
			}
			clickQueryBtn = true;
		}
		$("#pagingBar").empty();

		var totalCount = data.totalCount;
		if (totalCount > 0) {
			$("#pagingBar").append(data.pagingBar);
			$("#checkBoxAllAndDel").css("display","");
			$("#divMyWaybillHisContent").css("display","none");
		} else {
			if(bnos == '' || bnos == null){
				showNoWaybillHisRecord();
			}else{
				myWaybillHistoryTable.append(showNoWaybillState(bnos));
			}
		}
	}, function() {
		showNoWaybillHisRecord();
	});
	
	renderMouseEvent();
	
	var l = getL();
	if(2 != l) {
		$('input:checkbox[name="checkbox_waybill"]').remove();
		$("#selectAllAndDel").remove();
		$("#deleteWaybillHis").remove();
	}
	
	//显示产品名称
	var bnoAndProdName;
	if('bnos='==serachBnos || "bnos=undefined"==serachBnos){//点击运单查询或者翻页没输入运单号时还没有输入任何运单号,取用户查询历史的运单号
		serachBnos='bnos=';
		$('span[name=prodNames]').each(function(i, item) {
			var bnoid=item.id;//prodName_运单号
			var isExistProdName=item.textContent; 
			if(bnoid!=undefined && isExistProdName==''){
				bnoid=bnoid.substring(9);
				serachBnos=serachBnos+bnoid+',';
			}
			
		});
	}
	syncCallService("/service/waybill/prod/info", "post", dataType, serachBnos
			, function(data) {
				if(null!=data){
					$.each(data, function(i, item) {
						bnoAndProdName=item.split(",");
						if(bnoAndProdName[1]!="null"){
							$('#prodName_'+bnoAndProdName[0]).text('');
							$('#prodName_'+bnoAndProdName[0]).text(bnoAndProdName[1]);
						}
					});
				}
			}
	,function(){});
	
}

/**
 * 新版运单查询
 * @param bnos
 */
function getMyWaybillHistoryNew(bnos) {
	showLoading();
	showTipWithMsg(i18n.waybill_query_wait);
	
	$("#divMyWaybillHistory").empty();
	QUERY_UTILS.init(bnos);
	QUERY_UTILS.queryWayBillFromServer();
}


/**新版运单查询--start**/
var QUERY_UTILS = {};
QUERY_UTILS.query_param = null;
QUERY_UTILS.query_result = null;
QUERY_UTILS.query_headId = null;
QUERY_UTILS.bnos = null;

QUERY_UTILS.intervalArrays = [0,2000,4000];
QUERY_UTILS.times = 0;

QUERY_UTILS.init = function(bnos){
	QUERY_UTILS.query_param = '';
	QUERY_UTILS.query_result = '';
	QUERY_UTILS.query_headId = '';
	QUERY_UTILS.bnos = bnos;
	QUERY_UTILS.times = 0;
};

QUERY_UTILS.queryWayBillFromServer = function(){
    if(QUERY_UTILS.times < QUERY_UTILS.intervalArrays.length && !QUERY_UTILS.isQueryEnd()){
    	/*console.log('>>>>>>>>>>' + QUERY_UTILS.intervalArrays[QUERY_UTILS.times]);
    	console.log('do--------' + QUERY_UTILS.times);*/
    	QUERY_UTILS.query_param = "bnos=" + QUERY_UTILS.bnos + "&" 
    		+ "headId=" + QUERY_UTILS.query_headId + "&" + $("#myWaybillHistoryForm").serialize();
    	QUERY_UTILS.newQueryWaybill();
        setTimeout('QUERY_UTILS.queryWayBillFromServer()',QUERY_UTILS.intervalArrays[++QUERY_UTILS.times]);
    }else{
    	/*console.log('after do');*/
    	var showpicflag = true;
        if(QUERY_UTILS.isQueryEnd()){
        	QUERY_UTILS.drawTable(QUERY_UTILS.query_result.page,QUERY_UTILS.bnos);
        }else{
        	showpicflag = false;
        	sfAlert(i18n.waybill_query_fail);
        }
        closeLoading();
    	closeTip();
    	var type = getUrlParam("type");
    	var bno = getUrlParam("bno");
		if (showpicflag&&"2"==getL()&&"wbpic"==type&&
				!(bno == null || $.trim(bno) == null ||isNaN(bno))
				){
			showsignPic(bno);
		}
    }
};

QUERY_UTILS.isQueryEnd = function(){
	if(null == QUERY_UTILS.query_result) {
		console.log('server error');
		return false;
	}
	
	if('1' == QUERY_UTILS.query_result.status){
		QUERY_UTILS.query_headId = QUERY_UTILS.query_result.headId;
		return false;
	}
	
	if('2' == QUERY_UTILS.query_result.status){
		return true;
	}
	return false;
};

QUERY_UTILS.drawTable = function(page,bnos){
	var myWaybillHistoryTable = $("#divMyWaybillHistory");
	if(page.result != null && page.result != ''){
		$.each(QUERY_UTILS.query_result.page.result, function(i, item) {
			var location = (null == item.loaction) ? i18n.waybill_without_statusInfo : item.loaction;
			var state = (null == item.state) ? "4" : item.state;
			var sender = (null == item.sender) ? "" : item.sender;
			var receiver = (null == item.receiver) ? "" : item.receiver;
			// “0”=快件历史，“1”=快件结果
			var showClass = ("0" == item.isHistory) ? "" : "statesShow";
			var showDetail = ("0" == item.isHistory) ? "showDetailR" : "showDetailH";
			var th = '<div class="blockbox mt10">'
				+'<div class="blockbox-title title_style1">'
				+'<div class="block-title-ct clearfix">'
				+'<div class="ct-left">' +
				'<label>' +
				'<input type="checkbox" name="checkbox_waybill" value="'+item.bno+'" />' +
				'</label>' +
				'<span class="waybill-num">' + i18n.myorder_waybillno + i18n.symbol_colon + item.bno + '<span>(' + location + ')</span></span>' +
				'</div>'
				+'<div class="ct-right">' +
				'<a class="unl white mr30" href="/'+ i18n.name + '/subscription/mail_subscription.html?bno='+item.bno+'" >'+i18n.waybill_subscribe_email+'</a>' +
				'<a class="btn-statesInfoHide ' + showClass + '" title="'+i18n.waybill_view_details+'" id="'+showDetail+'"></a>' +
				'</div>'
				+'</div>'
				+'</div>';
			myWaybillHistoryTable.append(th + createWaybillRouteNode(item.bno, state, sender, receiver, item.steps, item.isHistory) + '</div>');
			showMiddleNode(item.bno, state, item.steps, 150);
		});
	}
	
	$("#pagingBar").empty();
	var totalCount = page.totalCount;
	if (totalCount > 0) {
		$("#pagingBar").append(page.pagingBar);
		$("#checkBoxAllAndDel").css("display","");
		$("#divMyWaybillHisContent").css("display","none");
	} else {
		if(bnos == '' || bnos == null){
			showNoWaybillHisRecord();
		}else{
			myWaybillHistoryTable.append(showNoWaybillState(bnos));
		}
	}
	
	renderMouseEvent();
	var l = getL();
	if(2 != l) {
		$('input:checkbox[name="checkbox_waybill"]').remove();
		$("#selectAllAndDel").remove();
		$("#deleteWaybillHis").remove();
	}
};

QUERY_UTILS.newQueryWaybill = function(){
	var url = "/service/waybill/n0login/history/new";
	var type = "get";
	var dataType = 'json';
	syncCallService(url, type, dataType, QUERY_UTILS.query_param, function(data) {
		QUERY_UTILS.query_result = data;
	}, function() {
	});
};

/**新版运单查询--end**/



/**
 * 创建路由节点线
 * 
 */
function createWaybillRouteNode(bno, state, sender, receiver, steps, isHistory) {
	if(steps == null || steps.length == 0) {
		return '';
	}
	// 圆点的宽度为11px
	var divWidth = (steps.length == 1) ? 11 : getWholeDivWidth(steps.length, state)/(steps.length-1);
	var lineWidth = divWidth - 11;
	// 查询结果显示明细，查询历史不显示明细。
	var displayOrNot = ("0" == isHistory) ? '' : 'style="display:none;"';
	var tr = '<div class="blockbox-c" ' + displayOrNot + '>' + '<div class="waybill-states clearfix">';//style="display:none;"
	$.each(steps, function(i, item) {
		var acceptTime = "";
		if(null != item.acceptTime) {
//			acceptTime = ("sc" == i18n.name) ? new Date(parseInt(item.acceptTime)).format("yyyy-MM-dd hh:mm:ss") :  getI18nFormatDateByLong(parseInt(item.acceptTime), true);
			acceptTime = item.acceptTime;
		}
		if((steps.length-1) == i) {
			tr = tr + '<div class="waybill-split last split-cur" >'
                    	+ fillNodeData("isLast", lineWidth, item.remark, acceptTime, item.acceptAddress, sender, receiver)
                    + '</div>';
		} else if(0 == i) {
			tr = tr + '<div class="waybill-split first" style="width:'+ divWidth + 'px;">'
                    	+ fillNodeData("isFirst", lineWidth, item.remark, acceptTime, item.acceptAddress, sender, receiver)
                    + '</div>';
		} else {
			tr = tr + '<div class="waybill-split mid" id="middle'+ bno + 'Node' + i + '" style="width:'+ divWidth + 'px;">'
                    	+ fillNodeData("isMiddle", lineWidth, item.remark, acceptTime, item.acceptAddress, sender, receiver)
                    + '</div>';
			
		}
	});
	tr = tr + '</div></div>';
	return tr;
}

/**
 * 描述：填充路由节点数据
 * nodePasition:节点位置
 * lineWidth：节点间连线的长度
 * remark：备注
 * acceptTime：时间
 * acceptAddress：位置（城市）
 * 
 */
function fillNodeData(nodePasition, lineWidth, remark, acceptTime, acceptAddress, sender, receiver) {
	var aTag = '', lineSpan = '', manP = '';
//	if("isMiddle" != nodePasition) {
//		aTag = '<a class="unl ml10" onclick="javascript:showEvaluation(this);">评价收派员</a>';
//	}
	if("isLast" != nodePasition) {
		lineSpan = '<span class="bar" style="width:'+ lineWidth + 'px;"></span>';
	}
	if ("isFirst" == nodePasition && null != sender && "" != sender) {
		manP = '<p class="man">' + i18n.waybill_sender + i18n.symbol_colon + sender + '</p>';
	} else if("isLast" == nodePasition && null != receiver && "" != receiver) {
		manP = '<p class="man">' + i18n.waybill_recipients + i18n.symbol_colon + receiver + '</p>';
	}
	acceptAddress = (acceptAddress == null) ? '' : acceptAddress;
	return '<div class="waybill-point clearfix"><span class="point"></span>' + lineSpan + '</div>'
         + '<div class="waybill-info">'
             + '<div class="info">'
                 + '<p class="top"><span class="state">' + remark + '</span>' + aTag + '</p>'
                 + '<p class="time">' + acceptTime + '</p>'
                 + '<p class="address">' + acceptAddress + '</p>'
                 + manP
             + '</div>'
         + '</div>';
}

/**
 * 显示“没有快件历史记录”
 */
function showNoWaybillHisRecord() {
	$("#divMyWaybillHisContent").empty();
	$("#checkBoxAllAndDel").css("display","none");
	var l = getL();
	if(0 != l) {
		$("#divMyWaybillHistory").empty();
		$("#divMyWaybillHistory").append('<div class="p10"><div class="attentionMsg"><div class="attentionIcon">' +
				'<p style="font-size:24px;">' + i18n.waybill_no_history + '</p>' +
				'</div></div></div>');
	} else {
		$("#divMyWaybillHisContent").append('<div class="p10"><div class="attentionMsg"><div class="attentionIcon">' +
									'<strong>' + i18n.waybill_tips +  i18n.symbol_colon + '</strong>' +
									i18n.waybill_log_tips + '<a class="unl" href="/' + i18n.name + '/user/register/register.html"> ' + i18n.waybill_registration + '</a>。' +
									'</div></div></div>');
	}
	
}

/**
 * 显示“没有快件状态信息”
 */
function showNoWaybillState(bnos) {
	$("#divMyWaybillHisContent").css("display","none");
	var th = '';
	for ( var i = 0; i < bnos.length; i++) {
		var tmpbno = bnos[i];
		if((typeof bnos)=="string")tmpbno = bnos;
		th = th + '<div class="blockbox mt10">'
			+'<div class="blockbox-title title_style1">'
				+'<div class="block-title-ct clearfix">'
					+'<div class="ct-left">' +
							'<span class="waybill-num">' + i18n.myorder_waybillno + i18n.symbol_colon + tmpbno + '<span>' + i18n.symbol_leftParenthesis + i18n.waybill_without_statusInfo + i18n.symbol_rightParenthesis + '</span></span>' +
					'</div>'
					+'<div class="ct-right">' +
						'<a class="unl white mr30" href="/'+ i18n.name + '/subscription/mail_subscription.html?bno='+tmpbno+'" >' + i18n.waybill_subscribe_email + '</a>' +
						'<a class="btn-statesInfoHide" title="' + i18n.waybill_view_details + '" id="showDetailH"></a>' +
					'</div>'
				+'</div>'
			+'</div></div>';
		if((typeof bnos)=="string")break;
	}
	return th;
}

/**
 * 描述：显示3个中间节点。
 * bno：运单号
 * steps：路由节点
 * firstBGWidth:第一个节点背景区宽度（默认140）
 * 
 */
function showMiddleNode(bno, bnoState, steps, firstBGWidth) {
	if(steps == null || steps.length <= 2) {
		return ;
	}
	var divWidth = getWholeDivWidth(steps.length, bnoState)/(steps.length-1);
	var i = 0, j = 1;
	var flag = ("4" == bnoState) ? 3 : 2;
	while(i < steps.length - 1 && flag > 0) {
		if((j-i) * divWidth > firstBGWidth) {
			// 显示节点
			$("#middle" + bno + "Node" + j).removeClass("waybill-split mid");
			$("#middle" + bno + "Node" + j).addClass("waybill-split first");
			i = j;
			flag --;
		} else {
			// 不显示节点
			j ++;
		}
	}
	
}

/**
 * 渲染“查看详细”，“鼠标移到节点显示背景色”事件
 * 
 */
function renderMouseEvent() {
	// 查询结果 操作效果
	$("#divMyWaybillHistory .blockbox").each(function() {
		// 查询结果
		var _click_target_R = $(this).find("#showDetailR");
		var _toggle_target_R = $(this).find(".blockbox-c");
		_click_target_R.toggle(function(){			
				$(this).addClass("statesShow");
				_toggle_target_R.hide();
		},function(){
				$(this).removeClass("statesShow");
				_toggle_target_R.show();
		});
		
		// 查询历史
		var _click_target_H = $(this).find("#showDetailH");
		var _toggle_target_H = $(this).find(".blockbox-c");
		_click_target_H.toggle(function(){			
				$(this).removeClass("statesShow");
				_toggle_target_H.show();
		},function(){
				$(this).addClass("statesShow");
				_toggle_target_H.hide();
		});
	});

	// 背景色
	$(".waybill-states .waybill-split").each(function(i) {
		$(this).hover(function(e) {
			if ($(this).hasClass("mid")) {
				$(this).find(".waybill-info").show();
			}
			$(this).find(".info").addClass("split-hover");
		}, function() {
			if ($(this).hasClass("mid")) {
				$(this).find(".waybill-info").hide();
			}
			$(this).find(".info").removeClass("split-hover");
		});
	});
}

/**
 * 根据路由节点数设定div的长度
 * 
 */
function getWholeDivWidth(stepsLength, bnoState) {
	if("4" == bnoState) {
		return 725;
	} else {
		if(2 == stepsLength) {
			return 270;
		} else if(3 == stepsLength) {
			return 410;
		} else {
			return 656;
		}
	}
}
function showsignPic(bno){
	stopTimer();
	$("#_send_verifycode").html("获取验证码");
	$("#_send_verifycode_span").attr("class","ui-btn btn-submits ml10");
	$("#_send_verifycode_span").data("active",true);
	//判断账单是否已签收&&登录手机号与运单收件号码匹配
	showLoading();
	showTipWithMsg(i18n.reprot_image_data_load);
	syncCallService("/service/waybillpic/prehandle?bno="+bno, "post", "json", "", function(result) {
		if("n0l0gin" == result){
			sfAlert("请登陆会员平台查看签收图，谢谢！");
			location.href = "/cn/sc/login.html?url=/cn/sc/waybill/waybill_query.html?wbpic="+bno;
		}else if(result.indexOf("mobilenotmatch_")!=-1){
//			var divSms = '<form class="reg-form" action="#" method="post">'+
//		    '    <ul>'+
//		    '	<li class="box"><input type="text" class="input-text" name="" placeholder="输入您寄件或收件的手机号码" value="" size="30" id="mobile" value="请输入您寄件或收件的手机号码" tip="请输入您寄件或收件的手机号码" nullmsg="请输入您寄件或收件的手机号码" /><span class="error" id="errorMsg"></span></li>'+
//		    '    <li class="box checkcode"><input type="text" class="input-text" name="" placeholder="请输入验证码" value="" size="10" id="code" /><a class="ui-btnm btn-submitm" href="javascript:void(0);" onclick="javascript:sendSMS();">获取验证码</a><span class="error" id="codeMsg"></span></li>'+
//		    '    <li class="box"><a class="ui-btn btn-login" href="javascript:void(0);" onclick="javascript:verifyCode();">下一步</a></li>'+
//		    '    </ul>'+
//		    '	<input type="hidden" id="bnoTmp" name="bnoTmp" value="'+bno+'"'+
//		    '</form>';
			$("#bnoTmp").val(bno);
			validMobile_signpic=art.dialog({
				title : '手机验证',
				padding:10,                                            
				lock:true,   
				content : document.getElementById('validMobile')
			});
			closeLoading();
			closeTip();
			return;
		}else if("forbidden" == result||"error" == result||"nobno" == result||"nopic" == result){
			sfAlert("非常抱歉，暂未能查询到"+bno+"的签收单信息，请稍后再尝试，谢谢！");
		}else if("notsign" == result){
			sfAlert("运单"+bno+"还未签收，暂时还没有回单图片，谢谢！");
		}else if("overdue" == result){
			sfAlert("运单"+bno+"已逾期，不能查看图片,谢谢！");
		}else{
			popPic(result,bno);
		}
		closeLoading();
		closeTip();
	},function(result) {
		closeLoading();
		closeTip();
		sfAlert("非常抱歉，暂未能查询到"+bno+"的回单图片信息，请稍后再尝试，谢谢！");
		return;
	});
}
function popPic(fileName,bno){
	var div = "运单号:"+bno+"的签收图</br>" +
		"<img style='width:400px;height:400px;' id='imgCode' alt='' src='/service/waybillpic/show?bno="+bno+"&fileUrl="+fileName+"'></br>" +
		"<a class='ui-btn btn-submits' href='javascript:downLoadPicture(\""+bno+"\")' id='loadBill'><span class='ui-btn-txt'>图片下载</span></a>"+
		"<a class='ui-btn btn-submits' href='javascript:getMailAddress(\""+bno+"\",\""+fileName+"\")' id='loadBill'><span class='ui-btn-txt'>发送邮箱</span></a>";
	$("#show_picture").html("");
	$("#show_picture").append(div);
	waybill_signpic=art.dialog({
		title : '回单图片',
		background : 'none',
		padding:10,  
		content : document.getElementById('show_picture')
	});
}
function downLoadPicture(wayBillNo){
	if(wayBillNo!=null||wayBillNo!=""){
		 showLoading(); 
		 showTipWithMsg(i18n.reprot_image_data_load);
		location.href="/service/waybillpic/download?bno="+wayBillNo;
		closeLoading();
		closeTip();
	}else{
		sfAlert(i18n.reprot_waybillNo_err_iamge_err);
	}
}
function getMailAddress(wayBillNo,fileName){
	if(wayBillNo!=null&&wayBillNo!=""){
		syncCallService('/service/waybillpic/getEmail?bno='+wayBillNo, 'get', 'json', null, function(data){
			if(data == 'N'){
				sfAlert("请先绑定邮箱！");
				window.location.href = '/' + i18n.name + '/user/emailbind/bind_email.html';
			}else if("forbidden" == data||"error" == data||"nobno" == data||"nopic" == data){
				sfAlert("非常抱歉，暂未能查询到"+wayBillNo+"的签收单信息，请稍后再尝试，谢谢！");
			}else if("notsign" == data){
				sfAlert("运单"+wayBillNo+"还未签收，暂时还没有回单图片，谢谢！");
			}else if("overdue" == data){
				sfAlert("运单"+wayBillNo+"已逾期，不能查看图片,谢谢！");
			}else if(isEmail(data)){
				sendEmailPicture(data,wayBillNo,fileName);
			}
		});
	}else{
		sfAlert(i18n.reprot_waybillNo_err_iamge_err);
	}
}
function sendEmailPicture(mailAddress,wayBillNo,fileName){

	showLoading(); 
	showTipWithMsg(i18n.reprot_image_data_load);
	syncCallService('/service/waybillpic/sendEmail?bno='+wayBillNo+'&fileUrl='+fileName+'&mailAddress='+mailAddress,
			'get',
			'json',
			'',
	function(data){
		if(data=='1'){
			sfAlert("图片已发送");
		}else if(data=='0'){
			sfAlert("图片发送失败,请稍后重试");
		}
	});
	closeLoading();
	closeTip();
	
}

function toCheckSignPic(){
	var wbno = getUrlParam("wbpic");
	if(!(wbno == null || $.trim(wbno) == null ||($.trim(wbno).length != 12 && $.trim(wbno).length != 0 && isNaN(wbno)))){
		return true;
	}
	return false;
}


//发送短信验证码
function sendSMS(){
	$("#errorMsg").text("");
	var mobile = $("#mobile").val();
	if(mobile==null || mobile.length == 0){
		$("#errorMsg").text('请输入手机号码');
		return;
	}
	if(isMobel(mobile) == false){
		$("#errorMsg").text('手机号码格式错误！请重新输入');
		return;
	}


	startTimer();
	var url = "/service/sendPhoneCode/waybillpic?phoneNo="+mobile;
	$.ajax({
		type : "POST",
		dataType : "json",
		url : url,
		success: function(code){
			if(code == "201"){
				alert("系统异常,请重试");
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			alert("服务器连接失败");
		}
	});
}
//验证手机和发送短信验证码
function verifyCode(){
	var mobile = $("#mobile").val();
	var code = $("#code").val();
	var bnoTmp = $("#bnoTmp").val();
	if(mobile==null || mobile.length == 0){
		$("#errorMsg").text('请输入手机号码');
		return;
	}
	if(isMobel(mobile) == false){
		$("#errorMsg").text('手机号码格式错误！请重新输入');
		return;
	}
	if(!/^\d{6}$/.test(code)){
		$("#codeMsg").text("请填写6位的验证码");
   		return;
   	}
	var url = "/service/verifyPhoneCode/waybillpic?phoneNo="+mobile+"&mobileVerifyCode="+code+"&bnoTmp="+bnoTmp;
	$.ajax({
		type : "post",
		dataType : "json",
		url : url,
		success: function(code){
			if(code=="201"){
				$("#errorMsg").text("手机号格式不正确");
			}else if(code == "202"){
				$("#codeMsg").text("验证码不正确");
			}else if(code == "203"){
				$("#codeMsg").text("验证码超时");
			}else if(code == "204"){
				$("#errorMsg").text("提交的手机号码和接收的手机号码不一致");
			}else if(code == "205"){
				$("#errorMsg").text("验证异常，请稍候重试！");
			}else if(code.indexOf("mobilenotmatch_")!=-1){
				$("#errorMsg").text("必须输入您寄件或收件的手机号码！");
			}else if("forbidden" == code||"error" == code||"nobno" == code||"nopic" == code){
				$("#errorMsg").text("非常抱歉，暂未能查询到"+bnoTmp+"的签收单信息，请稍后再尝试，谢谢！");
			}else if("notsign" == code){
				$("#errorMsg").text("运单"+bnoTmp+"还未签收，暂时还没有回单图片，谢谢！");
			}else if("overdue" == code){
				$("#errorMsg").text("运单"+bnoTmp+"已逾期，不能查看图片,谢谢！");
			}else{
				if(validMobile_signpic != undefined){
					validMobile_signpic.close();
				}
				popPic(code,bnoTmp);
			}/** 
			 * 201-手机号格式不正确;  
			 * 202-验证码不正确
			 * 203-验证码超时
			 * 204-提交的手机号码和接收验证码的手机号码不一致
			 * 205-验证异常
			 */
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			alert("服务器连接失败");
		}
	});
}

/**timer start**/

var initSec = 90;

var timer;
var sec;

var verifyCodeSpanID;
var verifyCodeBtnID;

function setTimer(){
	sec--;
	if (sec < 0) {
		stopTimer();
		$("#_send_verifycode").html("获取验证码");
		$("#_send_verifycode_span").attr("class","ui-btn btn-submits ml10");
		$("#_send_verifycode_span").data("active",true);
	} else {
		$("#_send_verifycode").html( sec + "秒后重新发送");
	}
}

function startTimer(){
	$("#_send_verifycode_span").data("active",false);
	sec = initSec;
	$("#_send_verifycode_span").attr("class","ui-btn btn-resets ml10");
	$("#_send_verifycode").html( sec + "秒后重新发送");
	timer = window.setInterval("setTimer()", 1000);
}

function stopTimer(){
	window.clearInterval(timer);
}

/**timer end**/

/** 验证邮箱 */
function isEmail(email) {
	var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
	if (reg.test(email)) {
		return true;
	} else {
		return false;
	}
}